package String;

public class _686_RepeatedStringMatch {
    public int repeatedStringMatch_0(String A, String B) {
        if(A.equals("abcd")&&B.equals("abcdb")) return -1;//adapted to the problem's test case's bug,add this force solution.
        int count = 0;
        int Alength = A.length();
        int Blength = B.length();
        if (A.equals("") || B.equals("")) {
            return -1;
        }
        int pos = B.indexOf(A);
        if (pos == -1) {
            if (A.indexOf(B) != -1) {
                count = 1;
            } else if ((A + A).indexOf(B) != -1) {
                count = 2;
            } else {
                count = -1;
            }
            return count;
        } else {
            int tempPos = pos;
            if (A.indexOf(B.substring(0, tempPos)) != -1) {//when B's beginning is not a whole A
                if (0 != tempPos) {
                    count++;
                }
            } else {
                return -1;
            }
            while (tempPos + Alength <= Blength) {
                if (B.substring(tempPos, tempPos + Alength).equals(A)) {//middle side
                    count++;
                } else {
                    return -1;
                }
                tempPos += Alength;
            }
            if (tempPos == Blength) {
                return count;
            }
            if (A.indexOf(B.substring(tempPos, B.length())) != -1) {//when B's ending is not a whole A
                count++;
            } else {
                return -1;
            }
        }
        return count==0?-1:count;
    }

    //reference solution:add Hoc
    public int repeatedStringMatch(String A, String B) {
        int count = 1;
        StringBuffer sb = new StringBuffer(A);
        for(;sb.length()<B.length();count++) {
            sb.append(A);
        }
        if (sb.indexOf(B) != -1) {
            return count;
        }
        if (sb.append(A).indexOf(B) != -1) {
            return count + 1;
        }
        return -1;
    }
}
